package cc.ufinity.networkdiagnose.manager;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.farproc.wifi.connecter.Wifi;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Handler;
import android.os.Parcelable;
import android.text.format.Formatter;
import cc.ufinity.networkdiagnose.view.R;

/**
 * 获取Wifi的AP，信号，RSSI等信息
 * 
 * @author ZR
 * 
 */
public final class WlanManager extends AbstractManager {

    public static final String SSID_CMCC_EDU = "CMCC-EDU";
    public static final String SSID_CMCC_AUTO = "CMCC-AUTO";
    public static final String SSID_CMCC = "CMCC";
    public static final String SSID_ChinaNet = "ChinaNet";
    public static final String SSID_ChinaUnicom1 = "ChinaUnicom";
    public static final String SSID_ChinaUnicom2 = "CU";
    
    public static final String TD = "HSDPA";
    public static final String GSM = "EDGE";
    
    // 扫描热点超时
    public static final int SCAN_TIMEOUT = 50000;
    // 获得热点后，连接超时
    public static final int CONNECT_TIMEOUT = 30000;
    
    private String gateWay;
    
    public String getGateWay() {
		return gateWay;
	}

	public void setGateWay(String gateWay) {
		this.gateWay = gateWay;
	}

	private WifiManager wifiManager;
    private WifiReceiver wifiReceiver;
    private DhcpReceiver dhcpReceiver;
    private PeapReceiver peapReceiver;
    private Peap2Receiver peapReceiver2;
    private ConnectivityManager connManager;
    private WifiInfo wifiInfo;
    private int cdmaDbm;
    public Task task;
    public boolean filter;
    public int flag = 3;
    
    

    public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public List<APInfo> apInfo;

    public int getCdmaDbm() {
        return cdmaDbm;
    }

    public void setCdmaDbm(int cdmaDbm) {
        this.cdmaDbm = cdmaDbm;
    }

    private int evdoDbm;

    public int getEvdoDbm() {
        return evdoDbm;
    }

    public void setEvdoDbm(int evdoDbm) {
        this.evdoDbm = evdoDbm;
    }

    public List<Map<String, Object>> wifiList;

    private WifiLock wifiLock;

    private Activity context;

    public Activity getContext() {
        return context;
    }

    private boolean isScanTimout = false;

    private static List<ScanResult> scanResults;
    private static ScanResult currentScanResult;

    public ScanResult getCurrentScanResult() {
        return currentScanResult;
    }

    public void setCurrentScanResult(ScanResult currentScanResult1) {
        currentScanResult = currentScanResult1;
    }

    public List<ScanResult> getScanResults() {
        return scanResults;
    }

    public void setScanResults(List<ScanResult> scanResults) {
        this.scanResults = scanResults;
    }

    private Handler wifiReceiverHandler;

    private long startConntectTime;// 记录开始连接网络时间点

    public long getStartConntectTime() {
        return startConntectTime;
    }

    public void setStartConntectTime(long startConntectTime) {
        this.startConntectTime = startConntectTime;
    }
    private long startDisConntectTime;// 记录开始断开网络时间点 
    
    public long getStartDisConntectTime() {
		return startDisConntectTime;
	}

	public void setStartDisConntectTime(long startDisConntectTime) {
		this.startDisConntectTime = startDisConntectTime;
	}

	private long connectedConsumeTime;// 连接消耗时间

    private String ipAddress;

    private int current;
    private int currentNetworkId;

    public int getCurrentNetworkId() {
        return currentNetworkId;
    }

    public void setCurrentNetworkId(int currentNetworkId) {
        this.currentNetworkId = currentNetworkId;
    }

    public int getCurrent() {   
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(int ipAddress) {
        this.ipAddress = this.toIPAdress(ipAddress);
    }

    public long getConnectedConsumeTime() {
        return connectedConsumeTime;
    }

    public void setConnectedConsumeTime(long connectedConsumeTime) {
        this.connectedConsumeTime = connectedConsumeTime;
    }

    public Handler getWifiReceiverHandler() {
        return wifiReceiverHandler;
    }

    public boolean isScanTimout() {
        return isScanTimout;
    }

    public void setScanTimout(boolean isScanTimout) {
        this.isScanTimout = isScanTimout;
    }

    public WlanManager(Activity context) {
        this.context = context;
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    	//取得ConnectivityManager对象
         connManager = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public WifiInfo getWifiInfo() {
        return wifiInfo;
    }

    public void openWifi() {
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    public void closeWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    public void lockWifi() {
        wifiLock = wifiManager.createWifiLock("WLAN_LOCK");
        wifiLock.acquire();
    }

    public void unlockWifi() {
        if (wifiLock.isHeld()) {
            wifiLock.acquire();
        }
    }
    /**
     * 打开Wifi并扫描指定SSID网络
     */
    public void openAndScanAP(){
    	 openWifi();
    }
    public void startScan() {
        openWifi();
        //stopScan();
        wifiReceiver = new WifiReceiver(this, wifiManager);
        wifiReceiver.setFlag(flag);
        context.registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        // 开始扫描热点
        boolean isStartScan = wifiManager.startScan();
        if(isStartScan) {
        	System.out.println("----------->>>>> 开始扫描热点 . . .");
        } else {
        	System.out.println("----------->>>>> 扫描热点失败  ! ! !");
        }
    }
    public void stopScan() {
    	try{
            context.unregisterReceiver(wifiReceiver);
    	}catch(Exception e){}
    }

    public List<Map<String, Object>> getWifiList() {
        return wifiList;
    }

    public void setWifiList(List<Map<String, Object>> result) {
        this.wifiList = result;
    }

    public String toIPAdress(final int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

    public WifiInfo getCurrentNetwork() {
        WifiInfo info = wifiManager.getConnectionInfo();
        return info;
    }
    
    // AP 关联测试，对CMCC,CMCC-EDU,CMCC-AUTO进行连接测试
    public void connect(final ScanResult scan) {
    	this.setStartConntectTime(System.currentTimeMillis());
    	wifiManager.disconnect();
    	System.out.println("wifiManager.getConnectionInfo():"+wifiManager.getConnectionInfo());
        unRegDhcpRecevier();
        dhcpReceiver = new DhcpReceiver(this, wifiManager);
        context.registerReceiver(dhcpReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        setCurrentScanResult(scan);
    	List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        enableNetwork(scan, configs);
    }
    public boolean isWifiEnabled() {
        return wifiManager.isWifiEnabled();
    }
    //对CMCC-AUTO进行连接测试
    public void connectPEAP(final ScanResult scan) {
    	this.setStartConntectTime(System.currentTimeMillis());
    	if(wifiManager.isWifiEnabled())
    		wifiManager.disconnect();
    	unRegReapRecevier();
    	peapReceiver = new PeapReceiver(this, wifiManager); 
        context.registerReceiver(peapReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        setCurrentScanResult(scan);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        enableNetwork(scan, configs); 
     //   this.setStartDisConntectTime(System.currentTimeMillis());
	//	wifiManager.disconnect(); 
    }
    /**
     * 对CMCC-AUTO进行断开连接测试
     * @param scan
     */
    public void disConnectPEAP(final ScanResult scan) {
    	unRegReap2Recevier();
    	peapReceiver2 = new Peap2Receiver(this, wifiManager); 
        context.registerReceiver(peapReceiver2, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        setCurrentScanResult(scan);
        this.setStartDisConntectTime(System.currentTimeMillis());
		wifiManager.disconnect(); 
    }
    
    /**
     * 判断是否存在某SSID网络的配置信息
     * @param SSID
     * @return
     */
    public boolean isExistConfig(String SSID){ 
    	//连接网络
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if(list !=null){
        	 for (int i = 0; i < list.size(); i++) { 
             	WifiConfiguration wifiConfiguration = list.get(i); 
             	if(wifiConfiguration.SSID != null && wifiConfiguration.SSID.equals("\"" + SSID + "\"")) {
                 		return true;
                 }           
              }
        }
        return false;
    }
    
    /**
     * 设置数据网络使用状态 
     * @param true 为可用 false为 不可用
     * @return 0为 成功 -1为失败
     */
     public int setMobileDataEnabled(boolean flag) { 
     	Method setMobileDataEnabl;
     	try {
 	    	setMobileDataEnabl = connManager.getClass().getDeclaredMethod(
 	    	"setMobileDataEnabled", boolean.class);
 	    	setMobileDataEnabl.invoke(connManager, flag);
 	    	return 0;
     	} catch (Exception e) {
     		e.printStackTrace();
     		return -1;
     	}
    }
     public boolean getMobileDataStatus(Context context) {
         ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

     Class<?> conMgrClass = null; // ConnectivityManager类
     Field iConMgrField = null; // ConnectivityManager类中的字段
     Object iConMgr = null; // IConnectivityManager类的引用
     Class<?> iConMgrClass = null; // IConnectivityManager类
     Method getMobileDataEnabledMethod = null; // setMobileDataEnabled方法
     
     try {
         // 取得ConnectivityManager类
         conMgrClass = Class.forName(conMgr.getClass().getName());
         // 取得ConnectivityManager类中的对象mService
         iConMgrField = conMgrClass.getDeclaredField("mService");
         // 设置mService可访问
         iConMgrField.setAccessible(true);
         // 取得mService的实例化类IConnectivityManager
         iConMgr = iConMgrField.get(conMgr);
         // 取得IConnectivityManager类
         iConMgrClass = Class.forName(iConMgr.getClass().getName());
         // 取得IConnectivityManager类中的getMobileDataEnabled(boolean)方法
         getMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("getMobileDataEnabled");
         // 设置getMobileDataEnabled方法可访问
         getMobileDataEnabledMethod.setAccessible(true);
         // 调用getMobileDataEnabled方法
         return (Boolean) getMobileDataEnabledMethod.invoke(iConMgr);
     } catch (ClassNotFoundException e) {
         e.printStackTrace();
        } catch (NoSuchFieldException e) {
         e.printStackTrace();
        } catch (SecurityException e) {
         e.printStackTrace();
        } catch (NoSuchMethodException e) {
         e.printStackTrace();
        } catch (IllegalArgumentException e) {
         e.printStackTrace();
        } catch (IllegalAccessException e) {
         e.printStackTrace();
        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                    }
            return false;
}

	/**
	 * 移动网络开关
	 */
	public void setMobileDataEnabled(Context context, boolean enabled) {
		ConnectivityManager conMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		Class<?> conMgrClass = null; // ConnectivityManager类
		Field iConMgrField = null; // ConnectivityManager类中的字段
		Object iConMgr = null; // IConnectivityManager类的引用
		Class<?> iConMgrClass = null; // IConnectivityManager类
		Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法

		try {
			// 取得ConnectivityManager类
			conMgrClass = Class.forName(conMgr.getClass().getName());
			// 取得ConnectivityManager类中的对象mService
			iConMgrField = conMgrClass.getDeclaredField("mService");
			// 设置mService可访问
			iConMgrField.setAccessible(true);
			// 取得mService的实例化类IConnectivityManager
			iConMgr = iConMgrField.get(conMgr);
			// 取得IConnectivityManager类
			iConMgrClass = Class.forName(iConMgr.getClass().getName());
			// 取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法
			setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod(
					"setMobileDataEnabled", Boolean.TYPE);
			// 设置setMobileDataEnabled方法可访问
			setMobileDataEnabledMethod.setAccessible(true);
			// 调用setMobileDataEnabled方法
			setMobileDataEnabledMethod.invoke(iConMgr, enabled);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}   

	/**
      * 检查网络连接情况
      * 
      * @return 0: None, 1、2: Wifi, 3、4: MOBILE_MMS, 5、6：MOBILE
      */
     public int checkNetworkType() {
         // if (Global.IsDebug)
         // return 1; 
         // 获取代表联网状态的NetWorkInfo对象
         NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
         // 获取当前的网络连接是否可用
         if (networkInfo == null || !networkInfo.isAvailable()) {
        	 return 0;
         }
             
         // Wifi
         State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
         if (State.CONNECTED == state) {
             return 1;
         }else if(State.CONNECTING == state) {
			 return 2;
		 } 
         // MOBILE_MMS
         state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getState();
         if (State.CONNECTED == state) {
             return 3;
         }else if(State.CONNECTING == state) {
			 return 4;
		 } 
         // MOBILE
         state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
         if (State.CONNECTED == state) {
             return 5;
         }else if(State.CONNECTING == state) {
			 return 6;
		 }
         return 7;
     }


    //获取指定SSID网络的当前连接状态
    public int currentNetWorkStatus(String SSID){  
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if(list !=null){
        	 for (int i = 0; i < list.size(); i++) { 
             	WifiConfiguration wifiConfiguration = list.get(i); 
             	if(wifiConfiguration.SSID != null && wifiConfiguration.SSID.equals("\"" + SSID + "\"")) {
                 		return wifiConfiguration.status;
                 }           
              }
        }
        return WifiConfiguration.Status.DISABLED;
    }
    
    private int getNetId(ScanResult scan, List<WifiConfiguration> wifiConfiguration){
    	int netId =-1;
    	for (WifiConfiguration c : wifiConfiguration) {
            if (c.SSID.equals("\"" + scan.SSID + "\"")) {
               netId = c.networkId;
            }
        }
    	return netId;
    }
    
    public void enableNetwork(ScanResult scan, List<WifiConfiguration> wifiConfiguration) {
        WifiConfiguration wcf = null;
        boolean exists = false;
        for (WifiConfiguration c : wifiConfiguration) {
            if (c.SSID !=null && c.SSID.equals("\"" + scan.SSID + "\"")) {
                wcf = c;
                exists = true;
                break;
            }
 
        }
 
        if (null == wcf) {
            wcf = new WifiConfiguration();
            wcf.BSSID = scan.BSSID;
            wcf.SSID = "\"" + scan.SSID + "\"";

            wcf.hiddenSSID = false;
            wcf.status = WifiConfiguration.Status.ENABLED;
            wcf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wcf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            wcf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wcf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wcf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wcf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            String mSecurity = scan.capabilities;
            // Log.e("secret", mSecurity);
            // 如果加密模式为WEP
            if (mSecurity.contains("WEP")) {
                wcf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wcf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                wcf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                // wcf.wepKeys[0] ="\"" + password + "\""; //This is the WEP
                // Password
                wcf.wepTxKeyIndex = 0;
            }
            // 如果加密模式为WPA EPA
            else if (mSecurity.contains("WPA-EAP")) {

            }
            // 如果加密模式为WPA PSK
            else if (mSecurity.contains("WPA-PSK")) {

            } else if (mSecurity.contains("WPA2-PSK")) {

            }
            // 无加密
            else {
                wcf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            }
        }
        int id = exists ? wcf.networkId : wifiManager.addNetwork(wcf);
       // wifiManager.enableNetwork(id, true);
        Wifi.connectToConfiguredNetwork(context, wifiManager, wcf, false);
    }
    
    public void registerRegDhcpRecevier(){
        
    }

    public void unRegDhcpRecevier() {
    	try {
    		context.unregisterReceiver(dhcpReceiver);
    	} catch(Exception e){}
    }
    public void unRegReapRecevier() {
    	try {
    		context.unregisterReceiver(peapReceiver);
    	} catch(Exception e){}
    }
    public void unRegReap2Recevier() {
    	try {
    		context.unregisterReceiver(peapReceiver2);
    	} catch(Exception e){}
    }
    public void disConnect() {
        wifiManager.disconnect();
    } 
}

final class DhcpReceiver extends BroadcastReceiver {
    private WlanManager wlanManager;
    private WifiManager wifiManager;

    public DhcpReceiver(WlanManager wlanManager, WifiManager wifiManager) {
        this.wlanManager = wlanManager;
        this.wifiManager = wifiManager; 
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // long start = System.currentTimeMillis();
    	Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
		if (null != parcelableExtra) {
			NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
			System.out.println("networkInfo.getState()--------"+networkInfo.getState());
		}
        int ip = wifiManager.getConnectionInfo().getIpAddress();
        if (ip != 0) {
            wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
            wlanManager.setIpAddress(ip);
            wlanManager.setCurrentNetworkId(wifiManager.getConnectionInfo().getNetworkId());
            DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
            wlanManager.setGateWay(Formatter.formatIpAddress(dhcpInfo.gateway));
            try {
            	wlanManager.unRegDhcpRecevier() ;
            } catch(Exception e) {
            	e.printStackTrace();
            }
            
            wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
        }      
    }

}

final class PeapReceiver extends BroadcastReceiver {
    private WlanManager wlanManager;
    private WifiManager wifiManager;
    public PeapReceiver(WlanManager wlanManager, WifiManager wifiManager) {
        this.wlanManager = wlanManager;
        this.wifiManager = wifiManager; 
    }

    @Override
    public void onReceive(Context context, Intent intent) {
    	 		// long start = System.currentTimeMillis();
         int ip = wifiManager.getConnectionInfo().getIpAddress();
         if (ip != 0) {
            wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
            wlanManager.setIpAddress(ip);
            wlanManager.setCurrentNetworkId(wifiManager.getConnectionInfo().getNetworkId());
            wlanManager.unRegReapRecevier();
            wlanManager.sendMsg(MessageWhat.PEAP_SUCESS_CONNECTED);
         }      
    }

}
final class Peap2Receiver extends BroadcastReceiver {
    private WlanManager wlanManager;
    private WifiManager wifiManager;
    public Peap2Receiver(WlanManager wlanManager, WifiManager wifiManager) {
        this.wlanManager = wlanManager;
        this.wifiManager = wifiManager; 
    }

    @Override
    public void onReceive(Context context, Intent intent) {
         int ip = wifiManager.getConnectionInfo().getIpAddress();
         if (!(ip != 0)) {
            wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
            wlanManager.setIpAddress(ip);
            wlanManager.setCurrentNetworkId(wifiManager.getConnectionInfo().getNetworkId());
            wlanManager.unRegReap2Recevier();
            wlanManager.sendMsg(MessageWhat.PEAP_SUCESS_DISCONNECTED);
         }      
    }

}
final class WifiReceiver extends BroadcastReceiver {
    private WlanManager wlanManager;
    private WifiManager wifiManager;
    
    private int flag;
	 

    public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public WifiReceiver(WlanManager wm, WifiManager wifiManager) {
        this.wlanManager = wm;
        this.wifiManager = wifiManager;
    }

    @Override
    public void onReceive(Context ctx, Intent intent) {
        List<ScanResult> scanResults = wifiManager.getScanResults();
        ComparatorLevel cl = new ComparatorLevel(flag);
        Collections.sort(scanResults, cl);
        wlanManager.setScanResults(scanResults);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        DBManager db = new DBManager((Activity) ctx);
        List<TaskConfig> tasks = db.getTask();
        db.release();
        for (ScanResult result : scanResults) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ssid", result.SSID);
            map.put("mac", result.BSSID);
            map.put("level", result.level + " dBm");
            map.put("xindao",getFrequency( result.frequency));
            map.put("snr", calcSNR(wlanManager.getCdmaDbm(), result.level));
            if (wlanManager.task != null) {
               /* if (db.taskFinished(tasks, result.BSSID, String.valueOf(wlanManager.task.id))) {
                    map.put("img", R.drawable.lock);
                    map.put("lock", "false");
                } else {
                    map.put("lock", "false");*/
                   if(result.level<-85){
                	   map.put("img", R.drawable.xh1);
                   }else if(result.level<-75){
                	   map.put("img", R.drawable.xh2);
                   }else if(result.level<-65){
                	   map.put("img", R.drawable.xh3);
                   }else if(result.level<-55){
                   		map.put("img", R.drawable.xh4);
                   }else if(result.level<-45){
                	   map.put("img", R.drawable.xh5);
                   }else{
                	   map.put("img", R.drawable.xh6);
                   }
              //  }
            } else {
               // map.put("lock", "false");
                
               if(result.level<-85){
            	   map.put("img", R.drawable.xh1);
               }else if(result.level<-75){
            	   map.put("img", R.drawable.xh2);
               }else if(result.level<-65){
            	   map.put("img", R.drawable.xh3);
               }else if(result.level<-55){
            	   map.put("img", R.drawable.xh4);
               }else if(result.level<-45){
            	   map.put("img", R.drawable.xh5);
               }else{
            	   map.put("img", R.drawable.xh6);
               }
            }
            map.put("scan", result);
            if (wlanManager.filter) {
                Iterator<APInfo> its = wlanManager.apInfo.iterator();
                APInfo info = null;
                while (its.hasNext()) {
                    info = its.next();
                    if (result.BSSID.equalsIgnoreCase(info.mac)) {
                        list.add(map);
                        break;
                    }
                }
            } else {
                list.add(map);
            }
        }
        
        wlanManager.setWifiList(list);
        wlanManager.sendMsg(MessageWhat.WIFI_RECEIVE_LIST);
        
        wlanManager.stopScan();  ////--------------------------
        System.out.println("----------->>>>> 接收WIFI_RECEIVE_LIST广播并发送消息。。。");
    }

    public int calcSNR(int pl, int pn) {
        // double snr = Math.abs(pl) / pn;
        // snr = 10 * Math.log10(snr);
        int snr = pl - pn;
        return snr;

    }
    
  //信道的转换
  	public int getFrequency(int a){
  		int channel=1;
  		 if(a==2412){
  			 channel=1;
  		}else if(a==2417){
  			 channel=2;
  		}else if(a==2422){
  			 channel=3;
  		}else if(a==2427){
  			 channel=4;
  		}else if(a==2432){
  			 channel=5;
  		}else if(a==2437){
  			 channel=6;
  		}else if(a==2442){
  			 channel=7;
  		}else if(a==2447){
  			 channel=8;
  		}else if(a==2452){
  			 channel=9;
  		}else if(a==2457){
  			 channel=10;
  		}else if(a==2462){
  			 channel=11;
  		}else if(a==2467){
  			 channel=12;
  		}else if(a==2472){
  			 channel=13;
  		}else if(a==2484){
  			 channel=14;
  		}
  	 return channel;
  	}

    private final class ComparatorLevel implements Comparator<ScanResult> {
    	private final static int SSID = 1;
    	private final static int MAC = 2;
    	private final static int LEVEL = 3;
    	private final static int CHANNLE = 4;
    	private int flag;
		public ComparatorLevel(int flag) {
			this.flag = flag;
		}

        @Override
        public int compare(ScanResult p1, ScanResult p2) {
          //  return String.valueOf(sr1.level).compareTo(String.valueOf(sr2.level));
        	
            if(flag == SSID) {
            	return (p1.SSID).compareToIgnoreCase(p2.SSID);
            } else if(flag == MAC) {
            	return (p1.BSSID).compareToIgnoreCase(p2.BSSID);
            } else if(flag == LEVEL) {
            	if((p1.level) > (p2.level)) {
            		return -1;
            	} else if((p1.level) == (p2.level)) {
            		return 0;
            	} else {
            		return 1;
            	}
            } else if(flag == CHANNLE) {
            	if((p1.frequency) > (p2.frequency)) {
            		return 1;
            	} else if((p1.frequency) == (p2.frequency)) {
            		return 0;
            	} else {
            		return -1;
            	}
            }
			
            return 0;
        }

    }
}
